<?php

namespace backend\module\content\controllers;

use Yii;
use backend\module\content\models\ContentCategory;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use backend\models\BackendUser;
/**
 * ContentCategoryController implements the CRUD actions for ContentCategory model.
 */
class ContentCategoryController extends BaseController {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
        ]);
    }
    /**
     * Lists all ContentCategory models.
     * @return mixed
     */
    public function actionIndex() {
        $data = ContentCategory::getAllData(BackendUser::getParentUserId());
        $nodeData = ContentCategory::getNodeGrid($data);
        $dataProvider = new ArrayDataProvider([
            'allModels' => $nodeData,
            'pagination' => false,
        ]);

//        $dataProvider = new ActiveDataProvider([
//            'query' => ContentCategory::find(),
//        ]);        

        return $this->render('index', [
                    'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single ContentCategory model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $request = Yii::$app->request;
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'title' => Yii::t('common', 'View'),
            'content' => $this->renderAjax('view', [
                'model' => $this->findModel($id),
            ]),
            'footer' => Html::button(Yii::t('common', 'Close'), ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
            Html::a(Yii::t('common', 'Edit'), ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
        ];
    }

    /**
     * Creates a new ContentCategory model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        Yii::trace($_SESSION, 'test');
        $request = Yii::$app->request;
        $model = new ContentCategory();
        $model->userid = BackendUser::getParentUserId();
        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        $nodeSelect = ContentCategory::getNodeSelect(
                        ContentCategory::getAllData(BackendUser::getParentUserId())
        );
        return $this->render('create', [
                    'model' => $model,
                    'nodeSelect' => $nodeSelect
        ]);
    }

    /**
     * Updates an existing ContentCategory model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $request = Yii::$app->request;
        $model = $this->findModel($id);

        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        $nodeSelect = ContentCategory::getNodeSelect(
                        ContentCategory::getAllData(BackendUser::getParentUserId())
        );
        return $this->render('update', [
                    'model' => $model,
                    'nodeSelect' => $nodeSelect
        ]);
    }

    /**
     * Delete an existing ContentCategory model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $request = Yii::$app->request;
        Yii::$app->response->format = Response::FORMAT_JSON;
        if (ContentCategory::isSubNode($id)) {
            return [
                'title' => "错误",
                'content' => '有子菜单所以不能删除',
            ];
        }
        $model = $this->findModel($id);
        
        $modelClass = "\\backend\\module\\content\\models\\". ucfirst($model->controller);
        if($result = $modelClass::find()->where(['catid'=>$id])->limit(1)->one()){
            Yii::trace($modelClass,'test');
            Yii::trace($result,'test');
            return [
                'title' => "错误",
                'content' => '分类下有文章不能删除',
            ];
        }
        
        $model->delete();
        return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
    }

    /**
     * Finds the ContentCategory model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ContentCategory the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        $userid = BackendUser::getParentUserId();
        if (($model = ContentCategory::findOne(['id'=>$id,'userid'=>$userid])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
